import React, { useCallback, useState, useRef } from 'react';
import { Button } from 'antd';
import PropTypes from 'prop-types';
import { createParamsUrl } from './util';
import styles from './index.less';

/**
 * 下载组件
 * @param {Object} params // 下载文件条件参数对象
 * @param {type} api // 业务查询的url
 *   两个场景  普通文件下载，带参数导出
 */
function fileDownload(props) {
  const [loading, setLoading] = useState(false);
  const iframeRef = useRef();
  const { params, style, api } = props;
  // 点击事件
  const onClick = useCallback(() => {
    setLoading(true);
    if (iframeRef && iframeRef.current) {
      iframeRef.current.src = api
        ? createParamsUrl(params, undefined, api)
        : createParamsUrl(params, 'download');
    }
    setTimeout(() => {
      setLoading(false);
    }, 500);
  }, [params]);
  return (
    <span className={styles.down}>
      <Button
        {...props}
        type={props.type || 'primary'}
        onClick={onClick}
        loading={loading}
        style={style}
      >
        {props.children}
      </Button>
      <iframe
        style={{ display: 'none' }}
        title={`download${props.name}`}
        ref={iframeRef}
      />
    </span>
  );
}

fileDownload.propTypes = {
  params: PropTypes.object,
  api: PropTypes.string,
  style: PropTypes.object,
};
export default fileDownload;
